﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Text.RegularExpressions;

namespace TestExcel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            excelApp = new Excel.Application();
        }

        static String filePath = "";
        static Excel.Application excelApp = null;
        static Excel.Workbook workBook = null;
        static Excel.Sheets sheets = null;
        static Excel.Worksheet workSheet = null;

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Excel files (*.xls;*.xlsx)|*.xls;*.xlsx|All files (*.*)|*.*";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (ofd.CheckFileExists)
                    {
                        filePath = ofd.FileName;
                        lblPath.Text = ofd.FileName;
                        
                        //// Open excel file
                        workBook = excelApp.Workbooks.Open(filePath, 0, true, 5,
                              "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
                              0, true);
                        sheets = excelApp.Worksheets;
                        workSheet = (Excel.Worksheet)sheets.get_Item(1);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            filePath = "";
            lblPath.Text = "";
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            try
            {
                int row = 1, col = 1;
                row = int.Parse(tbRow.Text);
                col = int.Parse(tbColumn.Text);

                //// Process the cell
                Excel.Range objRange = (Excel.Range)workSheet.Cells[row, col];
                lblResult.Text= objRange.Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }
    }
}
